<template>
	<view class="form-container">
		<!-- 表单主体 -->
		<scroll-view scroll-y class="form-body">
			<!-- 性别选择 -->
			<RadioGroup label="您的性别" v-model="form.gender" :options="[
			      { label: '男',type:'text', value: '男' },
			      { label: '女',type:'text', value: '女' }
			    ]" :required="true" />
			<!-- 年龄输入 -->
			<FormInput label="您的年龄" v-model="form.age" placeholder="请输入年龄" type="number"
				:required="true" />
			<!-- 手机号码 -->
			
			
			<!-- <view class="form-card">
				<text class="form-label required">手机号码</text>
				<view class="phone-input">
					<text class="prefix">+86</text>
					<input type="number" maxlength="11" placeholder="请输入11位手机号" v-model="form.phone" />
				</view>
				<view class="divider"></view>
			</view> -->
			<button class="button" :disabled="submitting" @click="submitForm">
				{{ submitting ? '提交中...' : '提交' }}
			</button>
		</scroll-view>
	</view>
</template>

<script>
	import RadioGroup from '../../components/RadioGroup.vue';
	import FormInput from '../../components/FormInput.vue';
	import FormInputWithButton from '../../components/FormInputWithButton.vue';
	import config from '../../config.js';
	
	export default {
		components: {
			RadioGroup,
			FormInput,
			FormInputWithButton
		},
		data() {
			return {
				submitting: false,
				form: {
					gender: uni.getStorageSync("gender"),
					age: uni.getStorageSync("age"),
				},
				countdown: 0
			}
		},
		created() {
			// 页面加载时补充：如果本地存储值为空，从身份证号提取
			this.fillFromIdCardIfEmpty();
		},
		methods: {
			fillFromIdCardIfEmpty() {
				// 获取身份证号
				console.log("idCard",uni.getStorageSync("idCard"));
				const idCard = uni.getStorageSync("idCard");
				if (!idCard) return; // 没有身份证号则退出
				
				// 处理性别：如果本地存储为空，从身份证号提取
				console.log(this.form.gender);
				if (!this.form.gender && this.isValidIdCard(idCard)) {
					const genderCode = parseInt(idCard.charAt(16), 10); // 第17位（索引16）
					this.form.gender = genderCode % 2 === 1 ? '男' : '女';
				}
				console.log(this.form.gender);
				// 处理年龄：如果本地存储为空，从身份证号提取
				if (!this.form.age && this.isValidIdCard(idCard)) {
					this.form.age = this.calculateAgeFromIdCard(idCard).toString();
				}
			},
			
			// 验证身份证号格式（18位）
			isValidIdCard(idCard) {
				const reg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
				return reg.test(idCard);
			},
			
			// 从身份证号计算年龄
			calculateAgeFromIdCard(idCard) {
				// 提取出生日期（第7-14位）
				const birthYear = parseInt(idCard.substring(6, 10), 10);
				const birthMonth = parseInt(idCard.substring(10, 12), 10);
				const birthDay = parseInt(idCard.substring(12, 14), 10);
				
				// 当前日期
				const today = new Date();
				const currentYear = today.getFullYear();
				const currentMonth = today.getMonth() + 1; // 月份从0开始，需+1
				const currentDay = today.getDate();
				
				// 计算年龄
				let age = currentYear - birthYear;
				
				// 如果今年生日还没过，年龄减1
				if (currentMonth < birthMonth || (currentMonth === birthMonth && currentDay < birthDay)) {
					age--;
				}
				
				return age;
			},
			
			// 表单验证
			validateForm() {
				const errors = {};
				
				// 必填字段验证
				const requiredFields = {
					gender: '性别',
					age: '年龄'
				};
				
				for (const [field, label] of Object.entries(requiredFields)) {
					if (label != '用户名' && !this.form[field]) {
						errors[field] = `${label}不能为空`;
					}
				}
				
				// 手机号验证
				if (this.form.phone && !/^1[3-9]\d{9}$/.test(this.form.phone)) {
					errors.phone = '请输入正确的手机号码';
				}
				
				// 年龄验证
				if (this.form.age && (isNaN(this.form.age) || this.form.age < 0 || this.form.age > 120)) {
					errors.age = '请输入正确的年龄';
				}
				
				this.formErrors = errors;
				return Object.keys(errors).length === 0;
			},
			
			// 准备提交数据
			prepareSubmitData() {
				// 处理更换周期，将天数转换为数字
				
				return {
					hospitalNumber:uni.getStorageSync("hospitalNumber"),
					gender: this.form.gender,
					age: this.form.age
				};
			},
			
			// 提交表单
			async submitForm() {
				if (this.submitting) return;
				
				if (!this.validateForm()) {
					uni.showToast({
						title: '请完善表单信息',
						icon: 'none'
					});
					return;
				}
				
				this.submitting = true;
				try {
					const submitData = this.prepareSubmitData();
					console.log("submitData is ", JSON.stringify(submitData))
					const response = await new Promise((resolve, reject) => {
					    uni.request({
					        url: `${config.baseUrl}/patient/changePatientInfo`,
					        method: 'POST',
					        data: submitData,
					        header: {
					          'Content-Type': 'application/json',
					          'Authorization': uni.getStorageSync('token') || ''
					        },
					        success: (res) => resolve(res),
					        fail: (err) => reject(err)
					    });
					});
					
					console.log('Response Status Code:', response.statusCode);
					console.log('Response Data:', response.data);
					    
					
					if (response.statusCode === 200 && response.data && response.data.code === 1) {
						// 成功的话要将修改后的值覆盖本地存储
						uni.setStorageSync("gender",this.form.gender)
						uni.setStorageSync("age",this.form.age)
						uni.setStorageSync("phone",this.form.phone)
						uni.setStorageSync('hasRegisteredInfo',1)
						// 重置表单
						this.resetForm();
						uni.switchTab({
						    url: '/pages/main/main'
						});
						//uni.setStorageSync('access', '1');
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});
					} else {
						throw new Error(response.data?.msg || '提交失败');
					}
				} catch (error) {
					console.error('提交表单错误:', error);
					uni.showToast({
						title: error?.message || '提交失败，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.submitting = false;
				}
			},
			
			// 重置表单
			resetForm() {
				this.form = {
					gender: uni.getStorageSync("gender"),
					age: uni.getStorageSync("age"),
					phone: uni.getStorageSync("phone"),
					verificationCode: ''
				};
				this.formErrors = {};
			}
		}
	}
</script>

<style lang="scss">
	.form-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding: 20rpx;

		.header {
			display: flex;
			align-items: center;
			padding: 30rpx 0;

			&-icon {
				width: 48rpx;
				height: 48rpx;
				margin-right: 15rpx;
			}

			&-text {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}

		.form-body {
			height: calc(100vh - 180rpx);
		}

		.form-card {
			background: white;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

			.form-label {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 30rpx;
				display: block;

				&.required::before {
					content: '*';
					color: #f44336;
					margin-right: 8rpx;
				}
			}

			.form-input {
				font-size: 30rpx;
				height: 80rpx;
				line-height: 80rpx;
			}

			.divider {
				height: 1rpx;
				background: #eee;
				margin: 20rpx -30rpx 0;
			}
		}
		.picker-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 30rpx;
			color: #666;
			height: 80rpx;
			line-height: 80rpx;

			.arrow-icon {
				width: 24rpx;
				height: 24rpx;
				opacity: 0.5;
			}
		}

		.placeholder-style {
			color: #bbb;
		}
	}
	.address-container {
		.icon-left {
			width: 32rpx;
			height: 32rpx;
			margin-right: 15rpx;
			opacity: 0.7;
		}

		.detail-input {
			margin-top: 20rpx;
			font-size: 28rpx;
			padding: 20rpx 0;
		}
	}

	.phone-input {
		display: flex;
		align-items: center;

		.prefix {
			color: #666;
			margin-right: 20rpx;
			font-size: 30rpx;
		}

		.form-input {
			flex: 1;
		}
	}
	.icon-right {
		width: 24rpx;
		height: 24rpx;
		opacity: 0.5;
	}
	.button{
		border-radius: 8px;
		background-color: #4361ee;
		color: white;
		width: 400rpx;
		margin-top: 50rpx;
	}
	
	.hospital-number-display {
	    font-size: 30rpx;
	    color: #333;
	    padding: 20rpx 0;
	    background: #f8f9fa; /* 可选：背景色与输入框一致 */
	    border-radius: 8rpx;
	}
</style>